'use client';

import React, { useState } from 'react';
import { Form, Input, Button } from 'antd';
import { MobileOutlined, SafetyOutlined } from '@ant-design/icons';
import { useMessage } from '@/hooks/useMessage';
import { useAuth } from '../../components/AuthProvider';
import { authApi } from '@/apis/auth';

interface TempUserInfo {
  phone: string;
  userId: string;
}

interface SmsLoginCardProps {
  onFirstTimeLogin?: (userInfo: TempUserInfo) => void;
}

interface SmsLoginForm {
  phone: string;
  code: string;
}

const SmsLoginCard: React.FC<SmsLoginCardProps> = ({ onFirstTimeLogin: _ }) => {
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const message = useMessage();
  const { smsLogin } = useAuth();

  // 发送验证码
  const sendSmsCode = async (phone: string) => {
    if (countdown > 0) return;
    
    try {
      // 调用发送短信验证码API
      await authApi.sendSmsCode(phone);
      message.success('验证码已发送');
      
      // 开始倒计时
      let count = 60;
      setCountdown(count);
      const timer = setInterval(() => {
        count -= 1;
        setCountdown(count);
        if (count <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } catch (error) {
      console.error('发送验证码失败:', error);
      message.error('验证码发送失败');
    }
  };

  // 短信登录
  const handleSmsLogin = async (values: SmsLoginForm) => {
    setLoading(true);
    try {
      const response = await smsLogin(values.phone, values.code);
      
      if (response && response.accessToken) {
        // 登录成功，已经在 AuthProvider 中处理了登录状态
        message.success('登录成功');
      } else {
        message.error('登录失败，请重试');
      }
    } catch (error) {
      console.error('登录失败:', error);
      message.error('登录失败，请检查手机号和验证码');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="w-full space-y-6">
      {/* 表单区域 */}
      <Form
        onFinish={handleSmsLogin}
        layout="vertical"
        className="space-y-4"
        size="large"
      >
        <Form.Item
          name="phone"
          rules={[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
          ]}
          className="mb-4"
        >
          <Input
            placeholder="请输入手机号"
            name="phone"
            prefix={<MobileOutlined className="text-gray-400" />}
            className="h-12 rounded-lg border-gray-200 focus:border-teal-500 focus:shadow-lg focus:shadow-teal-100 transition-all duration-300"
          />
        </Form.Item>

        <Form.Item
          name="code"
          rules={[{ required: true, message: '请输入验证码' }]}
          className="mb-4"
        >
          <div className="flex gap-3">
            <Input
              placeholder="请输入验证码"
              prefix={<SafetyOutlined className="text-gray-400" />}
              className="flex-1 h-12 rounded-lg border-gray-200 focus:border-teal-500 focus:shadow-lg focus:shadow-teal-100 transition-all duration-300"
            />
            <Button
              size="large"
              disabled={countdown > 0}
              onClick={() => {
                const form = document.querySelector('form') as HTMLFormElement;
                const phoneInput = form?.querySelector('input[name="phone"]') as HTMLInputElement;
                
                if (phoneInput?.value && /^1[3-9]\d{9}$/.test(phoneInput.value)) {
                  sendSmsCode(phoneInput.value);
                } else {
                  message.error('请先输入正确的手机号');
                }
              }}
              className="h-12 px-6 rounded-lg border-teal-500 text-teal-600 hover:bg-teal-50 hover:border-teal-600 transition-all duration-300 min-w-[120px]"
            >
              {countdown > 0 ? `${countdown}s` : '获取验证码'}
            </Button>
          </div>
        </Form.Item>

        <Form.Item className="mb-0">
          <Button
            type="primary"
            htmlType="submit"
            size="large"
            loading={loading}
            className="w-full h-12 rounded-lg bg-gradient-to-r from-teal-500 to-cyan-500 border-0 hover:from-teal-600 hover:to-cyan-600 shadow-lg hover:shadow-xl transition-all duration-300 font-medium"
          >
            {loading ? '登录中...' : '登录 / 注册'}
          </Button>
        </Form.Item>
      </Form>

      {/* 短信登录说明 */}
      <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 border border-blue-100">
        <div className="flex items-start space-x-3">
          <div className="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
            <MobileOutlined className="text-white text-xs" />
          </div>
          <div className="text-sm">
            <p className="text-blue-800 font-medium mb-1">短信登录说明</p>
            <ul className="text-blue-600 space-y-1 text-xs">
              <li>• 首次登录将自动创建账号</li>
              <li>• 验证码有效期为5分钟</li>
              <li>• 登录后可绑定微信账号</li>
            </ul>
          </div>
        </div>
      </div>

      {/* 安全提示 */}
      <div className="text-center">
        <div className="inline-flex items-center space-x-2 text-gray-500 text-xs">
          <SafetyOutlined />
          <span>您的手机号将被安全加密存储</span>
        </div>
      </div>
    </div>
  );
};

export default SmsLoginCard; 